﻿namespace PErsonMimi
{
    using System;
    using System.Reflection;
    using System.Collections;
    using System.IO;

    public class Ser
    {
        public static void Serialize(Object serializableObject)
        { 
            string[] objName = serializableObject.ToString().Split('.');
            string str = "<?xml version="+'"'+"1.0"+'"'+" encoding="+'"'+"utf-8"+'"'+"?>";
            Mainclass = objName[objName.Length - 1];
            str += "<" + Mainclass + Header;
            str += SerializeString(serializableObject);
            using (StreamWriter steamwWriter = File.CreateText("ser.xml"))
            {
                steamwWriter.WriteLine(str);
                steamwWriter.Close();
            }
           
        }
        public Person DSerialize(string deserializableString)
        {
            Person ret = null;
            deserializableString = "";
            string[] str = deserializableString.Split(' ');
            return ret;
        }
        private static string SerializeString(Object serializableObject)
        {
            string[] objName = serializableObject.ToString().Split('.');
            string str = "";
            if (objName[objName.Length - 1] != Mainclass)
            {
                str += "<" + objName[objName.Length - 1] + ">";
            }
            Type t = serializableObject.GetType();
            PropertyInfo[] pi = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);

            foreach (PropertyInfo pp in pi)
            {
                if (pp.PropertyType.IsGenericType)
                {
                    str += "<" + pp.Name.ToString() + ">";
                    var tmp = pp.GetValue(serializableObject, null);
                    foreach (object tmpObj in (tmp as IEnumerable))
                    {
                        str += SerializeString(tmpObj);
                    }
                    str += "</" + pp.Name.ToString() + ">";

                }
                else
                {
                    str += "<" + pp.Name.ToString() + ">";
                    str += pp.GetValue(serializableObject, new Object[] { });
                    str += "</" + pp.Name.ToString() + ">";
                }
            }
            str += "</" + objName[objName.Length - 1] + ">";
            return str;
        }
        private static string Header = " xmlns:xsi=" + '"' + "http://www.w3.org/2001/XMLSchema-instance" + '"' + " xmlns:xsd=" + '"' + "http://www.w3.org/2001/XMLSchema" + '"' + ">";
        private static string Mainclass { get; set; }
    }
}

